/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ejb;

import entities.Category;
import entities.User;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceProperty;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;

/**
 *
 * @author Alejandro
 */
@Stateless
public class CategoryBean implements CategoryBeanLocal {
  // @PersistenceUnit
    @PersistenceContext(unitName = "Retailshop-ejbPU")
    EntityManager manager;

    @Override
    public void insert(Category category) {
//       manager.getTransaction().begin();
        manager.merge(category);
//       manager.getTransaction().commit();
    }
//    @Override
//    public void begin(){
//        manager.getTransaction().begin();
//    }
//    @Override
//    public void commit(){
//        manager.getTransaction().commit();
//    }

    @Override
    public List<Category> findAllChildren() {
        Query query = manager.createNamedQuery("Category.findAllChildren");
        return (List<Category>) query.getResultList();
    }

    @Override
    public List<Category> findChildrenForParent() {
        Query query = manager.createNamedQuery("Category.findChildrenForParent");
        return (List<Category>) query.getResultList();
    }

    @Override
    public Category findByIdCategory(Integer idCategory) {
        Category res = null;
        Query query = manager.createNamedQuery("Category.findByIdCategory");
        query.setParameter("idCategory", idCategory);
        try {
            res = (Category) query.getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
        return res;
    }

    @Override
    public List<Category> findByIdParentCategory(Category idParentCategory) {
        List<Category> res = null;
        Query query = manager.createNamedQuery("Category.findByIdParentCategory");
        query.setParameter("parentCategory", idParentCategory);
        try {
            res = (List<Category>) query.getResultList();
        } catch (NoResultException e) {
            return null;
        }
        return res;
    }

    @Override
    public void markAsDelete(Category category) {
        category.setStatus(0);
        manager.merge(category);
    }
}
